<template>
  <div>
    <el-dialog
      v-model="open"
      width="65%"
      height="500px"
      :before-close="cancle"
      :title="title"
    >
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAddPackage">新增</el-button>
        </el-col>
        <el-col>
          <el-button :disabled="form.sysExpensesPayableList.length < 1" type="primary" @click="submit">保存</el-button>
        </el-col>
      </el-row>
      <el-form ref="formRef" :model="form">
        <vxe-grid
          ref="xGrids"
          v-loading="loading"
          show-footer
          :footer-method="getSummaries2"
          :data="form.sysExpensesPayableList"
          v-bind="gridOptions1"
          @edit-disabled="editDisabledEvent"
          @selection-change="handleSelectChange"
        >
          <template #serviceChannelCodes="{ row }">
            <vxe-select v-model="row.serviceChannelCode">
              <vxe-option
                v-for="dict in dicts[DictDirection.服务商]"
                :key="dict.providerServiceCode"
                placeholder="请选择服务商类型"
                :label="dict.serviceWholeName"
                :value="dict.providerServiceCode"
              >
              </vxe-option>
            </vxe-select>
          </template>
          <template #ladingNos="{ row }">
            <vxe-input v-model="row.ladingNo"></vxe-input>
          </template>
          <template #feeNames="{ row }">
            <vxe-select v-model="row.feeName">
              <vxe-option
                v-for="dict in dicts[DictDirection.费用名称]"
                :key="dict.feeValue"
                :label="dict.feeName"
                :value="dict.feeValue"
                :disabled="row.status ? row.status !== '待确认' : false"
              ></vxe-option>
            </vxe-select>
          </template>
          <template #unitPrices="{ row }">
            <vxe-input v-model="row.unitPrice"></vxe-input>
          </template>
          <template #numbers="{ row }">
            <vxe-input v-model="row.number"></vxe-input>
          </template>
          <template #amounts="{ row }">
            <vxe-input v-model="row.amount" disabled>
              {{ getSum(row) }}
            </vxe-input>
          </template>
          <template #currencys="{ row }">
            <vxe-select v-model="row.currency">
              <vxe-option 
                v-for="item in currencyList"
                :key="item.key"
                :label="item.label"
                :value="item.value"
              >
              </vxe-option>
            </vxe-select>
          </template>
          <template #exchangeRates="{ row }">
            <vxe-input v-model="row.exchangeRate"></vxe-input>
          </template>
          <template #remarks="{ row }">
            <vxe-input v-model="row.remark"></vxe-input>
          </template>
          <template #operate="{ row,$index }">
            <vxe-button
              title="删除"
              label="删除"
              circle
              @click="handleDel(row,$index)"
            >
              删除
            </vxe-button>
          </template>
        </vxe-grid>
      </el-form>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, getCurrentInstance, watch } from 'vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import { VxeGridInstance } from 'vxe-table'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { addPay, delPay, getPayList } from '@/api/expressManager/receivable'

const dicts = useDicts()
const xGrids = ref<VxeGridInstance>()
dicts.setDicts(DictDirection.费用名称)
dicts.setDicts(DictDirection.服务商)
const currencyList = ref([
  {
    value: '人民币',
    label: '人民币',
    key: 0,
  },
  {
    value: '美元',
    label: '美元',
    key: 1,
  },
]) 
const formRef = ref(undefined),
  {
    appContext: {
      config: {
        globalProperties: { $validateForm },
      },
    },
  } = getCurrentInstance()
const ids = ref(undefined),
  single = ref(true),
  multiple = ref(true)
const open = ref(false)
const title = ref(undefined)
const loading = ref(false)
const form = ref({
  sysExpensesPayableList: [{ serviceChannelCode: '', ladingNo: '', feeName: '', unitPrice: '', number: '', currency: '', amount: '', exchangeRate: '1' }],
  id: '',
  caseNo: '',
})
const gridOptions1 = reactive({
  border: true,
  showOverflow: true,
  sortConfig: {
    trigger: 'cell',
    remote: true,
  },
  columnConfig: {
    resizable: true,
  },
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    activeMethod({ columnIndex }) {
      if (columnIndex === 6) {
        return false
      }
      return true
    },
  },
  columns: [
    { type: 'checkbox', width: 50 },
    { field: 'serviceChannelCode', title: '服务商', editRender: {}, slots: { edit: 'serviceChannelCodes' } },
    { field: 'ladingNo', title: '提单号', editRender: {}, slots: { edit: 'ladingNos' } },
    { field: 'feeName', title: '费用名称', editRender: {}, slots: { edit: 'feeNames' } },
    { field: 'unitPrice', title: '单价', editRender: {}, slots: { edit: 'unitPrices' } },
    { field: 'number', title: '数量', editRender: {}, slots: { edit: 'numbers' } },
    { field: 'amount', title: '金额', editRender: {}, slots: { edit: 'amounts' } },
    { field: 'currency', title: '币种', editRender: {}, slots: { edit: 'currencys' } },
    { field: 'exchangeRate', title: '汇率', editRender: {}, slots: { edit: 'exchangeRates' } },
    { field: 'remark', title: '备注', editRender: {}, slots: { edit: 'remarks' } },
    { title: '操作', align: 'center', width: 100, slots: { default: 'operate' } },
  ],
})
const ladingNos = ref(undefined)
const caseNos = ref(undefined)
const idss = ref(undefined)
const { proxy } = getCurrentInstance() as any
const handleAddPackage = () => {
  const receivingWoodInfo = JSON.parse(JSON.stringify(form.value.sysExpensesPayableList))
  receivingWoodInfo.push({ serviceChannelCode: '', ladingNo: '', feeName: '', unitPrice: '', number: '', amount: '', currency: '人民币', exchangeRate: '1' })
  proxy.form.sysExpensesPayableList = receivingWoodInfo
}
const cancle = () => {
  open.value = false
  proxy.$refs.formRef.resetFields()
}
const submit = () => {
  form.value.id = idss.value
  form.value.caseNo = caseNos.value
  const data = form.value
  $validateForm(formRef.value, () => {
    loading.value = true
    addPay(data).then(res => {
      if (res.code == 200) {
        loading.value = false 
        ElMessage.success('添加成功')
        getList()
      } else {
        ElMessage.error(res.msg)
        loading.value = false
      }
    })
  })
}

const handleDel = (row: { [key: string]: any }, index) => {
  if (row.id == undefined) {
    const receivingWoodInfo = JSON.parse(JSON.stringify(form.value.sysExpensesPayableList))
    receivingWoodInfo.splice(index, 1)
    proxy.form.sysExpensesPayableList = receivingWoodInfo
  } else {
    ElMessageBox.confirm('此操作将永久删除该包裹信息, 是否继续?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      delPay(row.id).then(res => {
        if (res.code == 200) {
          form.value.sysExpensesPayableList.splice(index, 1)
          getList()
          ElMessage.success('删除成功')
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
  }
}
const getSummaries2 = () => {
  
}
const getSummaries = (param) => {
  const { columns } = param
  const RMB = 0
  const Dollar = 0
  proxy.form.sysExpensesPayableList
  .filter(ele => ele.currency === '人民币')
  .forEach(item => {
    proxy.RMB = item.amount + RMB
  })
  proxy.form.sysExpensesPayableList
  .filter(c => c.currency === '美元')
  .forEach(r => {
    proxy.Dollar = r.amount + Dollar
  })
  const sums = []
  const text1 = ' 人民币总计：'
  const price1 = ` ${ RMB.toFixed(2) }`
  const text2 = '美元总计：'
  const price2 = `  ${ Dollar.toFixed(2) }`
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = (() => {
        const el = text1
        return el
      })()
    } else if (index === 1) {
      sums[index] = (() => {
        const el = price1
        return el
      })()
    } else if (index === 2) {
      sums[index] = (() => {
        const el = text2
        return el
      })()
    } else if (index === 3) {
      sums[index] = (() => {
        const el = price2
        return el
      })()
    } 
  })
  return sums
}
watch(() => form.value.sysExpensesPayableList,
  (news, olds) => {
    if (news != olds) {
      getSum()
    }
  }, {
    deep: true,
  })
const getSum = (row: { [key: string]: any }) => {
  console.log(row)
  
  row.amount = ''
  console.log(111)
  
  if (row.unitPrice == undefined || row.number == undefined) {
    // eslint-disable-next-line no-return-assign
    return (row.amount = 0)
  } 
  // eslint-disable-next-line no-return-assign
  return (row.amount = row.number * row.unitPrice)
}
const handleSelectChange = (row: { [key: string]: any }) => {
  ids.value = row.map(el => el.id)
  single.value = row.length != 1
  multiple.value = !row.length
}
const getList = () => {
  const ladingNo = ladingNos.value
  getPayList(ladingNo).then(res => {
    proxy.form.sysExpensesPayableList = res.data
  })
}
defineExpose({
  getList,
  open,
  title,
  ladingNos,
  idss,
  caseNos,
})
</script>
